<template>
    <div>
        <el-page-header class="mt-0 mb-2" @back="back">
            <template #title>
                <div class="v-center">
                    <div>基本信息</div>
                    <el-icon class="cursor-pointer ml-2" @click.stop="showEdit"><Edit /></el-icon>
                </div>
            </template>
        </el-page-header>
        <div class="base-info bg-main p-4 br-1">
            <el-row class="lh-3">
                <el-col :span="field.span || 8" v-for="field in fields" :key="field.prop">
                    <label>{{ field.label }}：</label>
                    <el-icon v-if="field.type == 'iconSelector'"><component :is="appInfo[field.prop]" /></el-icon>
                    <span v-else-if="field.converter">{{ field.converter(appInfo[field.prop], appInfo) }}</span>
                    <span v-else-if="!field.render">{{ appInfo[field.prop] }}</span>
                    <base-render v-else :content="field.render(appInfo[field.prop], appInfo)"></base-render>
                </el-col>

                <el-col :span="8">
                    <label>应用id：</label>
                    <span>{{ appInfo.id }}</span>
                    <el-link type="primary" class="ml-4" icon="DocumentCopy" @click="copyId"></el-link>
                </el-col>
                <el-col :span="8">
                    <label>应用密钥：</label>
                    <template v-if="appInfo.secret">
                        <el-link icon="DocumentCopy" type="primary" @click="doCopy"></el-link>
                        <el-link type="primary" class="ml-4" @click="generateSecret">重新生成</el-link>
                    </template>

                    <el-link type="primary" v-else @click="generateSecret">生成</el-link>
                </el-col>
            </el-row>
        </div>

        <div class="mt-2 pt-0">
            <el-tabs>
                <el-tab-pane label="应用菜单">
                    <appMenu :appId="id" v-if="id" class="br-1 bg-main p-4"></appMenu>
                </el-tab-pane>
                <el-tab-pane label="应用授权">
                    <el-tabs class="bg-main px-4 py-2 br-1" :style="{ height }">
                        <el-tab-pane label="角色授权" class="h-100">
                            <Role :appId="id" />
                        </el-tab-pane>
                        <el-tab-pane label="机构授权">
                            <Dept :appId="id" />
                        </el-tab-pane>
                        <el-tab-pane label="用户授权">
                            <User :appId="id" />
                        </el-tab-pane>
                    </el-tabs>
                </el-tab-pane>

                <el-tab-pane label="数据订阅">
                    <DataSub :appInfo="appInfo" class="bg-main br-1 p-4" v-if="appInfo.id" />
                </el-tab-pane>
            </el-tabs>
        </div>

        <!-- <div class="text-center mt-4">
            <el-button @click="back" icon="close">关闭</el-button>
        </div> -->

        <el-drawer v-model="visible" title="应用编辑">
            <base-form :fields="fields" v-model="appInfo" labelPosition="top" ref="formRef" />
            <template #footer>
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="save">确定</el-button>
            </template>
        </el-drawer>
    </div>
</template>
<script setup>
import { onMounted } from "vue";
import { ElTag } from "element-plus";
import BaseRender from "@/components/base-render.js";
import appMenu from "./app-menu.vue";
import * as _ from "lodash";
import Role from "./role.vue";
import Dept from "./dept.vue";
import User from "./user.vue";
import { useSysStore } from "../../../../store";
import DataSub from "./data-sub.vue";

const fields = ref([
    {
        label: "应用分类",
        prop: "categoryId",
        required: true,
        type: "select",
        options: loadCategory,
        converter: (val, row) => row.categoryName || "--",
        change: (val, form, { item }) => {
            if (!val) {
                form.categoryName = "--";
            } else {
                form.categoryName = item.name;
            }
        },
    },
    { label: "编码", prop: "code", required: true, width: "140px" },
    { label: "名称", prop: "name", required: true },
    {
        label: "状态",
        prop: "status",
        needNew: false,
        width: "100px",
        render: (val) => {
            if (val) {
                return h(ElTag, { type: "primary" }, () => "上架");
            } else {
                return h(ElTag, { type: "danger" }, () => "下架");
            }
        },
        display: false,
    },
    { label: "图标", prop: "icon", type: "iconSelector", width: "80px", align: "center" },
    {
        label: "支持平台",
        prop: "platform",
        type: "radioGroup",
        options: [
            { label: "PC", value: "pc" },
            { label: "APP", value: "app" },
            { label: "h5", value: "h5" },
            { label: "微信小程序", value: "mp" },
        ],
        default: "pc",
        width: "120px",
        converter: (val) => {
            return val == "pc" ? "PC" : val == "app" ? "APP" : val == "h5" ? "H5" : "微信小程序";
        },
    },
    { label: "应用地址", prop: "url", required: false, remark: "如果是外部应用，请填写正确的应用地址" },
    {
        label: "打开方式",
        prop: "openType",
        type: "radioGroup",
        options: [
            { label: "当前窗口", value: "inner" },
            { label: "新窗口", value: "new" },
        ],
        default: "inner",
        width: "120px",
        converter: (val) => (val == "inner" ? "当前窗口" : val == "new" ? "新窗口" : "全屏"),
    },
    { label: "排序", prop: "sort", default: "0", width: "80px", remark: "此处为字符串升级排序方式" },
    { label: "备注", prop: "remark", type: "textarea", span: 24 },
]);
const appInfo = ref({});
const visible = ref(false);
const formRef = ref();
const { id } = defineProps({
    id: String,
});
const emits = defineEmits(["close", "reload"]);
const sysStore = useSysStore();
const height = computed(() => {
    if (sysStore.tagTabsVisible()) {
        return "calc(100vh - 510px)";
    } else {
        return "calc(100vh - 470px)";
    }
});

onMounted(() => {
    app.https.get("/sys/app/detail/" + id).then((resp) => {
        if (!resp.metadata) {
            resp.metadata = {};
        }

        if (!resp.metadata.webhooks) {
            resp.metadata.webhooks = {};
        }

        appInfo.value = resp;
    });
});

let bak;
function showEdit() {
    bak = _.cloneDeep(appInfo.value);
    visible.value = true;
}

function loadCategory() {
    return app.https.post("/sys/app-category/query");
}

function cancel() {
    appInfo.value = bak;
    visible.value = false;
}

function save() {
    formRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https.put("/sys/app/update", appInfo.value).then(() => {
            app.success("操作成功");
            visible.value = false;
            emits("reload");
        });
    });
}

function generateSecret() {
    let func = () => {
        app.https.get("/sys/app/regenerate-secret", { id: appInfo.value.id }).then((resp) => {
            appInfo.value.secret = resp;
            app.success("生成成功");
        });
    };

    if (!appInfo.value.secret) {
        func();
    } else {
        app.confirm("确定重新生成密钥？生成后原密钥将作废").then(() => {
            func();
        });
    }
}

function doCopy() {
    copyToClipboard(appInfo.value.secret);
}

function copyId() {
    copyToClipboard(appInfo.value.id);
}

function copyToClipboard(text) {
    // 尝试使用 Clipboard API
    if (navigator.clipboard) {
        return navigator.clipboard.writeText(text).then(app.success);
    }

    // 降级方案：使用 execCommand
    const textarea = document.createElement("textarea");
    textarea.value = text;
    textarea.style.position = "fixed"; // 避免滚动影响
    document.body.appendChild(textarea);
    textarea.select();
    const success = document.execCommand("copy");
    document.body.removeChild(textarea);
    if (success) {
        app.success();
    }
}

function back() {
    emits("close");
}
</script>
